import React, { useEffect, useState } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import { Down } from '@react-vant/icons';
import { FloatingPanel, Toast } from 'react-vant';
import './AddAddress.css';
import { useNavigate } from 'react-router-dom';
import axios from '../../utils/index'

export default function Address() {
    let map = null;
    let marker = null;
    const navigate = useNavigate();
    const [selectedAddress, setSelectedAddress] = useState('');
    const [aname,setAname] = useState('')
    const [mapLoaded, setMapLoaded] = useState(false);

    useEffect(() => {
        window._AMapSecurityConfig = {
            securityJsCode: "e8cb186db8ce345f8f09f4253d6e8d1e",
        };
        AMapLoader.load({
            key: "93ac23764b679a2cfd4c8887ab99e648 ", 
            version: "2.0",
            plugins: ["AMap.Scale"],
        })
            .then((AMap) => {
                map = new AMap.Map("mapContainer", {
                    viewMode: "3D",
                    zoom: 11,
                    center: [116.397428, 39.90923],
                });

                // 添加地图点击事件监听器
                map.on('click', function(e) {
                    // 使用逆地理编码获取经纬度对应的地址名称
                    AMap.plugin('AMap.Geocoder', function () {
                        const geocoder = new AMap.Geocoder({
                            // 是否进行逆地理编码
                            // 如果设置为 true，将会返回详细的地址信息
                            // 如果设置为 false，则只返回逆地理编码后的地址名称
                            batch: false,
                        });
                        
                        // 调用逆地理编码服务
                        geocoder.getAddress([e.lnglat.lng, e.lnglat.lat], function (status, result) {
                            if (status === 'complete' && result.info === 'OK') {
                                // 将地址名称设置为选定的地址
                                setSelectedAddress(result.regeocode.formattedAddress);
                                // 清除之前的标记
                                if (marker) {
                                    marker.setMap(null);
                                }
                                // 在点击的位置添加标记
                                marker = new AMap.Marker({
                                    position: e.lnglat,
                                    map: map,
                                });
                            }
                        });
                    });
                });
            })
            .catch((e) => {
                console.log(e);
            });

        return () => {
            map?.destroy();
        };
    }, []);

    const handleAddAddress = () => {
        // 处理添加地址逻辑
        axios.post('/addAddress',{"aname":aname,"address":selectedAddress}).then(res => {
            if(res.data.code === 200) {
                Toast("添加成功")
                setSelectedAddress('')
                setAname('')
            }
        })
    };

    return (
        <div id='add'>
            <div className='my_add_header'>
                <Down fontSize={30} style={{ transform: 'rotate(90deg)' }} onClick={() => { navigate('/address') }} />
                <h2>添加新地址</h2>
            </div>
            <div id="mapContainer" style={{ width: '100%', height: '550px' }} />
            <div className='my_add_content'>
                <FloatingPanel anchors={[170, 360, window.innerHeight * 0.8]}>
                    <div className='my_add_content_item'>
                        <h2>详细地址</h2>
                        <hr style={{ marginTop: '20px' }} />
                        <div className='add' style={{ width: 'calc(100% - 40px)', minHeight: '80px', padding: '0 20px', marginTop: '30px' }}>
                            <h3>地址名称</h3>
                            <input type="text" value={aname} onChange={(ev)=>{setAname(ev.target.value)}}/>
                            <h3>详细地址</h3>
                            <input type="text" value={selectedAddress} readOnly />
                            <button className='add_btn' onClick={handleAddAddress}>添加地址</button>
                        </div>
                    </div>
                </FloatingPanel>
            </div>
        </div>
    );
}
